package com.wing.product.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.device.model.entity.DeviceCategory;
import com.wing.dict.model.entity.DictLabel;
import com.wing.dict.service.DictLabelService;
import com.wing.platform.order.model.response.ProductSyncVO;
import com.wing.product.model.entity.*;
import com.wing.product.model.response.ProductTypeVO;
import com.wing.product.model.response.WarehouseAreaSkuItermVo;
import com.wing.product.service.*;
import com.wing.purchase.model.entity.SupplierInfo;
import com.wing.purchase.service.SupplierInfoService;
import com.wing.storage.model.entity.ProductInventory;
import com.wing.storage.service.ProductInventoryService;
import com.wing.storage.service.WarehouseAreaSkuItermService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.excel.ProductDetailExcelIn;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 产品明细管理
 *
 * @author xiayang
 */
@Slf4j
@Validated
@Api(value = "Admin-产品明细表管理", tags = "#/product/productDetailWMS")
@RestController("productDetailWMSController")
@RequestMapping("product/admin/productDetailWMS")
@RequiredArgsConstructor
public class ProductDetailWMSController {

    private final ProductDetailService productDetailService;

    @Autowired
    private DictLabelService dictLabelService;

    @Autowired
    private ProductTypeService productTypeService;

    @Autowired
    private ProductBrandService productBrandService;

    @Autowired
    private SupplierInfoService supplierInfoService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @Autowired
    private ProcessLineTemplateService processLineTemplateService;

    @Autowired
    private ProcessLineTemplateRecordService processLineTemplateRecordService;

    //库存表
    @Autowired
    private ProductInventoryService productInventoryService;
    @Autowired
    private ProductUnitService productUnitService;

    @Autowired
    private WarehouseAreaSkuItermService warehouseAreaSkuItermService;


    @ApiOperation(value = "查询所有产品明细表", notes = "搜索")
    @GetMapping("/list")
    public PageResult<ProductDetail> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,
            String materialNature,
            Long productTypeId,
            String skuName,
            String skuCode,
            String pricingMethod,
            String skuSpec,
            String excludeId,
            String productCategoryId,
            String notInListIds,
            String inIds,
            Long warehouseId,
            String keyWord
            ) {
        Page<ProductDetail> pg = new Page<>(page, limit);
        Map<String,Object> map = new HashMap();
        map.put("order", order);
        map.put("materialNature", materialNature);
        map.put("productTypeId", productTypeId);
        map.put("pricingMethod", pricingMethod);
        map.put("excludeId", excludeId);
        map.put("skuName", skuName);
        map.put("skuSpec", skuSpec);
        map.put("keyWord", keyWord);
        map.put("productCategoryId", productCategoryId);
        map.put("skuCode", skuCode);
        if (StringUtils.isNotBlank(notInListIds)) {
            String[] lists = notInListIds.split(",");
            map.put("notInListIds", lists);
        }

        if (StringUtils.isNotBlank(inIds)) {
            String[] ids = inIds.split(",");
            map.put("inIds", ids);
        }

        //查询库存
        List<ProductInventory> inventoryList = productInventoryService.list();

        IPage<ProductDetail> list = productDetailService.pageList4app(pg, map);
        List<ProductDetail> records = list.getRecords();
        records.forEach(info -> {
            info.setCodeAndName(info.getSkuCode() + "(" + info.getSkuName() + ")");
            if (ObjectUtil.isNotEmpty(warehouseId)) {
                //查询库存分布 根据仓库id
                List<WarehouseAreaSkuItermVo> finalVo = warehouseAreaSkuItermService.getAreaSkuItermInfoBy(warehouseId);
                if (CollectionUtils.isNotEmpty(finalVo)) {
                    for (WarehouseAreaSkuItermVo warehouseAreaSkuItermVo : finalVo) {
                        if (warehouseAreaSkuItermVo.getProductDetailId().equals(info.getId())) {
                            info.setHaveQuantity(BigDecimal.valueOf(warehouseAreaSkuItermVo.getHaveQuantity()));
                        }
                    }
                }
            }else {
                for (ProductInventory productInventory : inventoryList) {
                    if (productInventory.getProductDetailId().equals(info.getId())) {
                        info.setHaveQuantity(productInventory.getQuantity());
                    }
                }
            }
        });


        return new PageResult<>(records, list.getTotal());
    }

    @ApiOperation(value = "添加产品明细表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(ProductDetail productDetail) {
        LambdaQueryWrapper<ProductDetail> query = new LambdaQueryWrapper<ProductDetail>();
        query.eq(ProductDetail::getSkuCode, productDetail.getSkuCode());
        List<ProductDetail> productDetailList = productDetailService.list(query);
        if (CollectionUtils.isNotEmpty(productDetailList)) {
            return JsonResult.fail("SKU编码已存在！");
        }
        //工艺线路-工序列表
        List<ProcessLineTemplateRecord> processLineTemplateRecordList = processLineTemplateRecordService.list();
        //SKU工序集
        List<ProcessLineTemplateRecord> recordList = processLineTemplateRecordList.stream().filter(t -> t.getProcessLineTemplateId().longValue() == productDetail.getProductProcessLineId().longValue()).collect(Collectors.toList());
        String skuProcessCode = "";
        for (int k = 0; k < recordList.size(); k++) {
            if (k == 0) {
                skuProcessCode = recordList.get(k).getProcessId() + "";
            } else {
                skuProcessCode += "," + recordList.get(k).getProcessId();
            }
        }
        productDetail.setSkuProcessCode(skuProcessCode);
        if (productDetailService.save(productDetail)) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "修改产品明细表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(ProductDetail productDetailParam) {
        ProductDetail productDetail = productDetailService.getById(productDetailParam.getId());
        if (productDetail == null) {
            return JsonResult.fail("修改失败，产品明细不存在");
        }
        //工艺线路-工序列表
        List<ProcessLineTemplateRecord> processLineTemplateRecordList = processLineTemplateRecordService.list();
        //SKU工序集
        List<ProcessLineTemplateRecord> recordList = processLineTemplateRecordList.stream().filter(t -> t.getProcessLineTemplateId().longValue() == productDetailParam.getProductProcessLineId().longValue()).collect(Collectors.toList());
        String skuProcessCode = "";
        for (int k = 0; k < recordList.size(); k++) {
            if (k == 0) {
                skuProcessCode = recordList.get(k).getProcessId() + "";
            } else {
                skuProcessCode += "," + recordList.get(k).getProcessId();
            }
        }
        productDetailParam.setSkuProcessCode(skuProcessCode);
        if (productDetailService.updateById(productDetailParam)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "删除产品明细表", notes = "删除")
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long productDetailId) {
        if (productDetailService.removeById(productDetailId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "流水号查询", notes = "搜索")
    @GetMapping("/serialNumber")
    public JsonResult serialNumber(@RequestParam("productCode") String productCode) {
        QueryWrapper<ProductDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("sku_code", productCode);
        List<ProductDetail> list = productDetailService.list(queryWrapper);
        List<Integer> array = new ArrayList<>();
        if (list != null && list.size() > 0) {
            //String top = "";
            List<String> skuCodes = list.stream().map(d -> d.getSkuCode()).collect(Collectors.toList());
            for (String skuCode : skuCodes) {
                String[] split = skuCode.split("-");
                //top = split[0];
                String temp = split[split.length - 1];
                if (temp.length() == 3) {
                    Integer integer = Integer.valueOf(temp);
                    array.add(integer);
                }
            }
            //取最大值
            Integer max = array.stream().reduce(array.get(0), Integer::max);
            Format f1 = new DecimalFormat("000");
            String format = f1.format(max + 1);
            String s = productCode + "-" + format;
            return JsonResult.success(s);
        } else {
            return JsonResult.success(productCode + "-001");
        }
    }

    @ApiOperation(value = "查询产品明细", notes = "搜索")
    @GetMapping("/get")
    public JsonResult get(@RequestParam("productDetailId") Long productDetailId) {
        //产品明细
        ProductDetail productDetail = productDetailService.get4appById(productDetailId);

        return JsonResult.success(productDetail);
    }

    /**
     * 下载物料录入excel模板
     */
    @ApiOperation(value = "下载物资类别录入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 字典数据
        List<DictLabel> dictLabelList = dictLabelService.list(null);

        String[] headerArr = {"料号名称(*)", "料号(*)", "货品编码", "国标条码", "历史品名", "历史料号", "规格码(*)", "物料类别性质(*)", "所属类别(*)", "物料分类(*)", "品牌", "主计量单位(*)", "基础单位换算率(*)", "计价币种", "税率", "是否自产产品", "产品性质(*)", "是否委外生产", "工艺线路", "成本价", "是否可以销售", "销售指导价", "长度(mm)", "宽度(mm)", "高度(mm)", "重量(克)", "安全库存阈值", "采购周期(天)", "呆滞时长阈值(天)", "质保期(天)", "折旧时长(月)", "数据来源(*)", "是否一物一码(*)", "是否批次管理", "是否先进先出", "助记码", "成本核算方式", "参考成本", "最新成本", "备注"};
        List<String[]> downData = new ArrayList<>();
        List<String> indexArr = new ArrayList<>();
        StringBuffer tempStr = new StringBuffer();

        //物料类别性质
        List<DictLabel> natureList = dictLabelList.stream().filter(t -> "sys_product_type_nature".equals(t.getDictType())).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(natureList)){
            for (DictLabel nature : natureList) {
                tempStr.append(nature.getLabelName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("7");
        }

        //所属类别
        QueryWrapper<ProductType> productTypeQueryWrapper = new QueryWrapper<>();
        List<ProductType> productTypeList = productTypeService.list(productTypeQueryWrapper);
        if(CollectionUtil.isNotEmpty(productTypeList)){
            for (ProductType productType : productTypeList) {
                tempStr.append(productType.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("8");
        }

        //物料分类
        QueryWrapper<ProductCategory> productCategoryQueryWrapper = new QueryWrapper<>();
        productCategoryQueryWrapper.eq("is_final", 1);
        List<ProductCategory> productCategoryListList = productCategoryService.list(productCategoryQueryWrapper);
        if(CollectionUtil.isNotEmpty(productCategoryListList)){
            for (ProductCategory productCategory : productCategoryListList) {
                tempStr.append(productCategory.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("9");
        }

        //品牌
        QueryWrapper<ProductBrand> productBrandQueryWrapper = new QueryWrapper<>();
        List<ProductBrand> productBrandList = productBrandService.list(productBrandQueryWrapper);
        if(CollectionUtil.isNotEmpty(productBrandList)){
            for (ProductBrand productBrand : productBrandList) {
                tempStr.append(productBrand.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("10");
        }

        //计量单位

        List<String> strings = productUnitService.getUnitByGrounp();
        if(CollectionUtil.isNotEmpty(strings)){
            for (String unitName : strings) {
                tempStr.append(unitName).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("11");
        }
        //计价币种
        List<DictLabel> priceCurrencyList = dictLabelList.stream().filter(t -> "sys_product_detail_price_currency".equals(t.getDictType())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(priceCurrencyList)) {
            for (DictLabel dictLabel : priceCurrencyList) {
                tempStr.append(dictLabel.getLabelName()).append(",");
            }
            tempStr.delete(tempStr.length() - 1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0, tempStr.length());
            indexArr.add("13");
        }
        //是否自产产品
        String[] yesNodata = new String[]{"是", "否"};
        for (String yesNodatum : yesNodata) {
            tempStr.append(yesNodatum).append(",");
        }
        tempStr.delete(tempStr.length() - 1, tempStr.length());
        downData.add(yesNodata);
        tempStr.delete(0, tempStr.length());
        indexArr.add("15");

        //产品性质
        List<DictLabel> productNatureList = dictLabelList.stream().filter(t -> "product_nature".equals(t.getDictType())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(productNatureList)) {
            for (DictLabel dictLabel : productNatureList) {
                tempStr.append(dictLabel.getLabelName()).append(",");
            }
            tempStr.delete(tempStr.length() - 1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0, tempStr.length());
            indexArr.add("16");
        }

        //是否委外生产
        for (String yesNodatum : yesNodata) {
            tempStr.append(yesNodatum).append(",");
        }
        tempStr.delete(tempStr.length() - 1, tempStr.length());
        downData.add(yesNodata);
        tempStr.delete(0, tempStr.length());
        indexArr.add("17");

        //工艺线路
        QueryWrapper<ProcessLineTemplate> processLineTemplateQueryWrapper = new QueryWrapper<>();
        List<ProcessLineTemplate> processLineTemplateList = processLineTemplateService.list(processLineTemplateQueryWrapper);
        if (CollectionUtil.isNotEmpty(processLineTemplateList)) {
            for (ProcessLineTemplate processLineTemplate : processLineTemplateList) {
                tempStr.append(processLineTemplate.getName()).append(",");
            }
            tempStr.delete(tempStr.length() - 1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0, tempStr.length());
            indexArr.add("18");
        }
        //是否可以销售
        for (String yesNodatum : yesNodata) {
            tempStr.append(yesNodatum).append(",");
        }
        tempStr.delete(tempStr.length() - 1, tempStr.length());
        downData.add(yesNodata);
        tempStr.delete(0, tempStr.length());
        indexArr.add("20");

        //数据来源
        List<DictLabel> dataSourceList = dictLabelList.stream().filter(t -> "sys_product_detail_data_source".equals(t.getDictType())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(dataSourceList)) {
            for (DictLabel dictLabel : dataSourceList) {
                tempStr.append(dictLabel.getLabelName()).append(",");
            }
            tempStr.delete(tempStr.length() - 1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0, tempStr.length());
            indexArr.add("31");
        }
        //是否一物一码
        for (String yesNodatum : yesNodata) {
            tempStr.append(yesNodatum).append(",");
        }
        tempStr.delete(tempStr.length() - 1, tempStr.length());
        downData.add(yesNodata);
        tempStr.delete(0, tempStr.length());
        indexArr.add("32");
        //是否批次管理
        for (String yesNodatum : yesNodata) {
            tempStr.append(yesNodatum).append(",");
        }
        tempStr.delete(tempStr.length() - 1, tempStr.length());
        downData.add(yesNodata);
        tempStr.delete(0, tempStr.length());
        indexArr.add("33");
        //是否先进先出
        for (String yesNodatum : yesNodata) {
            tempStr.append(yesNodatum).append(",");
        }
        tempStr.delete(tempStr.length() - 1, tempStr.length());
        downData.add(yesNodata);
        tempStr.delete(0, tempStr.length());
        indexArr.add("34");

        //成本核算方式
        List<DictLabel> costCheckTypeList = dictLabelList.stream().filter(t -> "product_detail_cost_check_type".equals(t.getDictType())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(costCheckTypeList)) {
            for (DictLabel dictLabel : costCheckTypeList) {
                tempStr.append(dictLabel.getLabelName()).append(",");
            }
            tempStr.delete(tempStr.length() - 1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0, tempStr.length());
            indexArr.add("36");
        }
        DownExcelUtil.createExcelTemplate(response, request, "物料导入模板", Arrays.asList(headerArr), downData, indexArr);
    }

    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<ProductDetailExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<ProductDetailExcelIn> list = reader.read(is, ProductDetailExcelIn.class);
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            productDetailService.importExcel(list);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }

}
